# import hashlib
# import hmac
# import time
# import json
# import base64
# import urllib.parse
# import logging
# from cryptography.hazmat.primitives.asymmetric import rsa, padding
# from cryptography.hazmat.primitives import hashes
# from cryptography.hazmat.backends import default_backend
#
# logging.basicConfig(level=logging.DEBUG)
# logger = logging.getLogger(__name__)
#
# # 支付宝配置
# ALIPAY_CONFIG = {
#     'app_id': '2021000148608903',
#     'merchant_private_key': '''-----BEGIN RSA PRIVATE KEY-----
# MIIEpQIBAAKCAQEAp/W3i8D3JTdyNVQNag6TxhKd2mwxeT0TfbEhmA/1X0ChCwluij7MN4Kz9LXF9JWCsyOojZz1jb4z4V6oHOO6yqhqrkFQRy+vGTwbai6FZg0jf6unDgCuybj/Y/mh+ndjBakJcuoq8wDimGlEt1ZbpsVwPeMjklsIUrudt8rUwLjNMHlk7XF1MEzJto0U9tCkZObPItez1FWZZkacB2AHRyuodGb4JBJ5bvJ4mGDuIBU/P/2uMTpc4rgwMHC9Xb40Nz+MuyLVk9md1rCDTooJK2cysFiXlNAVRCXqSWovV/7AjKrxqV9kcJ2MiVB1ERJGPkG2/Vfa00hEZUQ3QOz2lwIDAQABAoIBAQCJNLhRCTycAXRhzhz7M5dSKmkbQmET+mnOtwGLeBXpTyF/o5/SfURUYIhjco6Yo/5WGt4ZeUw7E1LMW4gXuY0g+n3ThfVvgauXgLugfQpqeHc0V2QrkzE2BtNSt12z/w08VX8ridG2G1YATZZd8sUCMq3jUIcBiy38b9mCh8ZO/BWIp7W5pqnDxTRZ7Y6QWJfbGh2H3GikmRbOMLaZwUfUv2lOlJjUuHEoBfNHbO52JNWRMNPV0MBSXs7ngGXk7z20IdLSDU5USE+L9c7+NpZ71kyn4mlvQ0ZLfe9vB5gyKmOD27J2a6Xnsiw7OVV9EzwwWiBqKsljmBaxnpLJTOuBAoGBANJVkyGdt75inQAeh4333vSmTCarYExXJH4tdJwPHgJQEQd23aENorcQpYtO6gc0bGYIzqu3lXgH02mSi4SqGc+ItwyDnimg7jgP0RxJHxTJHhC4u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l/cUkXFl9pGbQV4WQA7F2/ArKUY3xuXft6J00Qoo+cPHJp6Eh2wCkP2KIFkzY1WLHHGevuMFqcuqI/Auequk1HWsrAhCodioh3Tsp4G35kELuzs1fhZrLz56MhsoYRWt5UUhsuchjDk4cwIDAQAB
# -----END PUBLIC KEY-----''',
#     'sign_type': 'RSA2',
#     'gateway_url': 'https://openapi-sandbox.dl.alipaydev.com/gateway.do',
#     'notify_url': 'http://localhost:8000/api/alipay/notify',
#     'return_url': 'http://localhost:8000/api/alipay/return',
#     'seller_id': '2088721065233465',
# }
#
#
# def generate_sign(params, private_key):
#     """生成签名 (使用 pycryptodome 实现)"""
#     try:
#         # 1. 过滤空值参数
#         filtered_params = {k: v for k, v in params.items() if v is not None and v != '' and k != 'sign'}
#
#         # 2. 按字典序排序并拼接
#         sorted_params = sorted(filtered_params.items(), key=lambda x: x[0])
#         message = '&'.join(f'{k}={str(v)}' for k, v in sorted_params)
#
#         # 记录待签名字符串
#         logger.debug(f"待签名字符串: {message}")
#
#         # 3. 加载私钥并签名
#         private_key = RSA.import_key(private_key)
#         h = SHA256.new(message.encode('utf-8'))
#         signature = pkcs1_15.new(private_key).sign(h)
#
#         # 4. Base64编码
#         sign = base64.b64encode(signature).decode('utf-8')
#         logger.debug(f"签名结果: {sign}")
#
#         return sign
#     except Exception as e:
#         logger.error(f"生成签名失败: {str(e)}")
#         raise
#
#
# def verify_sign(params, public_key):
#     """验证签名 (使用 pycryptodome 实现)"""
#     try:
#         sign = params.get('sign', None)
#         sign_type = params.get('sign_type', 'RSA2')
#
#         if not sign:
#             logger.error("缺少签名参数")
#             return False
#
#         # 复制参数并移除签名相关字段
#         verify_params = params.copy()
#         verify_params.pop('sign', None)
#         verify_params.pop('sign_type', None)
#
#         # 过滤空值参数并排序
#         filtered_params = {k: v for k, v in verify_params.items() if v is not None and v != ''}
#         sorted_params = sorted(filtered_params.items(), key=lambda x: x[0])
#         message = '&'.join(f"{k}={v}" for k, v in sorted_params)
#
#         # 记录待验证字符串
#         logger.debug(f"待验证字符串: {message}")
#         logger.debug(f"收到的签名: {sign}")
#
#         # 加载公钥并验证
#         public_key = RSA.import_key(public_key)
#         h = SHA256.new(message.encode('utf-8'))
#         signature = base64.b64decode(sign)
#
#         # 尝试验证签名
#         try:
#             pkcs1_15.new(public_key).verify(h, signature)
#             logger.debug("签名验证成功")
#             return True
#         except (ValueError, TypeError) as e:
#             logger.error(f"签名验证失败: {str(e)}")
#             return False
#
#     except Exception as e:
#         logger.error(f"验证签名过程中出错: {str(e)}")
#         return False
#
#
# def create_alipay_order(order_number, total_amount, subject='商品购买', body='商品详情'):
#     """创建支付宝支付订单"""
#     try:
#         # 构建业务参数
#         biz_content = {
#             'out_trade_no': order_number,
#             'product_code': 'FAST_INSTANT_TRADE_PAY',
#             'total_amount': str(total_amount),
#             'subject': subject,
#             'body': body,
#             'seller_id': ALIPAY_CONFIG['seller_id']
#         }
#
#         # 构建请求参数
#         params = {
#             'app_id': ALIPAY_CONFIG['app_id'],
#             'method': 'alipay.trade.page.pay',
#             'format': 'JSON',
#             'return_url': ALIPAY_CONFIG['return_url'],
#             'charset': 'utf-8',
#             'sign_type': 'RSA2',
#             'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
#             'version': '1.0',
#             'notify_url': ALIPAY_CONFIG['notify_url'],
#             'biz_content': json.dumps(biz_content, ensure_ascii=False),
#         }
#
#         # 生成签名
#         sign = generate_sign(params, ALIPAY_CONFIG['merchant_private_key'])
#         params['sign'] = sign
#
#         # 构建请求URL (不需要单独编码 biz_content)
#         query_string = '&'.join(f"{k}={urllib.parse.quote_plus(str(v))}" for k, v in params.items())
#         pay_url = f"{ALIPAY_CONFIG['gateway_url']}?{query_string}"
#
#         return pay_url
#     except Exception as e:
#         logger.error(f"创建支付宝订单失败: {str(e)}")
#         raise
#
#
# def query_order(order_number):
#     """查询支付宝订单状态"""
#     try:
#         biz_content = {'out_trade_no': order_number}
#
#         params = {
#             'app_id': ALIPAY_CONFIG['app_id'],
#             'method': 'alipay.trade.query',
#             'format': 'JSON',
#             'charset': 'utf-8',
#             'sign_type': ALIPAY_CONFIG['sign_type'],
#             'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
#             'version': '1.0',
#             'biz_content': json.dumps(biz_content)
#         }
#
#         # 生成签名
#         sign = generate_sign(params, ALIPAY_CONFIG['merchant_private_key'])
#         params['sign'] = sign
#
#         # 发送请求
#         import requests
#         response = requests.post(ALIPAY_CONFIG['gateway_url'], data=params)
#
#         # 验证响应签名
#         response_data = response.json()
#         alipay_response = response_data.get('alipay_trade_query_response', {})
#
#         if alipay_response.get('code') != '10000':
#             logger.error(f"支付宝查询失败: {alipay_response.get('msg', '未知错误')}")
#             return alipay_response
#
#         # 验证签名
#         if not verify_sign(alipay_response, ALIPAY_CONFIG['alipay_public_key']):
#             logger.error("支付宝响应签名验证失败")
#             return {'error': '签名验证失败'}
#
#         return alipay_response
#     except Exception as e:
#         logger.error(f"查询订单失败: {str(e)}")
#         raise


#
# import hashlib
# import hmac
# import time
# import json
# import base64
# import urllib.parse
# import logging
# # 导入 pycryptodome 的正确模块（注意首字母大写）
# from Crypto.Signature import PKCS1_v1_5  # 修正导入名称（pkcs1_15 → PKCS1_v1_5）
# from Crypto.Hash import SHA256
# from Crypto.PublicKey import RSA
# from Crypto import Random  # 可选，如需随机数生成
#
# logging.basicConfig(level=logging.DEBUG)
# logger = logging.getLogger(__name__)
#
# # 支付宝配置（保持不变）
# # 支付宝配置
# ALIPAY_CONFIG = {
#     'app_id': '2021000148608903',
#     'merchant_private_key': '''-----BEGIN RSA PRIVATE KEY-----
# MIIEpQIBAAKCAQEAp/W3i8D3JTdyNVQNag6TxhKd2mwxeT0TfbEhmA/1X0ChCwluij7MN4Kz9LXF9JWCsyOojZz1jb4z4V6oHOO6yqhqrkFQRy+vGTwbai6FZg0jf6unDgCuybj/Y/mh+ndjBakJcuoq8wDimGlEt1ZbpsVwPeMjklsIUrudt8rUwLjNMHlk7XF1MEzJto0U9tCk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n3hE7JMlLPR/f6CMhjt4t86tzwJA9splnZTskgQ7SCzXAXOYnDpyI8Mj8NNYAPecPiBpWfpiRGPnmJyty+qX6BcB1uWNcnRJGNXzYe6guUkvFAJrqoxZHFbQaatUjvLSECzOXIECgYEAsWd+/ToPuMYcZckKOTsIrGg9C/K/yeSoD6P0N8cHCxx7aw0+8SANt8X7mOsKZ6a3btw8F7iJXo8Eh10PU7X57sK6DiAp25FUSNvDQZlZsMcMAbzA7r7zx26n4Ms/mGQeY8uuOdlsm1UCdF7S9MPQDSNZ4zisdgULIYUbl+j0NJw=
# -----END RSA PRIVATE KEY-----''',
#     'alipay_public_key': '''-----BEGIN PUBLIC KEY-----
# MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvSwDmEnAvDH30S36Ms0Dg4p3+ZenPWJFVLbaY7UbS/4orWti5470Pg5qnKQ2TDrQpx1N9oE8zKLtIcYLMFBOvfm5GbWvrNyp1UXHWDeF5jh9/JeTtDs5yQ+ewWbAk+Z8iKOXUOeoyetsNI6SmFg0Qqdh1yAynJ5DEiETPA9MImbgk2teU9SYCsqNPeMH+lrCZTJQq3dFl/cUkXFl9pGbQV4WQA7F2/ArKUY3xuXft6J00Qoo+cPHJp6Eh2wCkP2KIFkzY1WLHHGevuMFqcuqI/Auequk1HWsrAhCodioh3Tsp4G35kELuzs1fhZrLz56MhsoYRWt5UUhsuchjDk4cwIDAQAB
# -----END PUBLIC KEY-----''',
#     'sign_type': 'RSA2',
#     'gateway_url': 'https://openapi-sandbox.dl.alipaydev.com/gateway.do',
#     'notify_url': 'http://localhost:8000/api/alipay/notify',
#     'return_url': 'http://localhost:8000/api/alipay/return',
#     'seller_id': '2088721065233465',
# }
#
#
# def generate_sign(params, private_key):
#     """生成签名 (使用 pycryptodome 实现)"""
#     try:
#         # 1. 过滤空值参数
#         filtered_params = {k: v for k, v in params.items() if v is not None and v != '' and k != 'sign'}
#
#         # 2. 按字典序排序并拼接
#         sorted_params = sorted(filtered_params.items(), key=lambda x: x[0])
#         message = '&'.join(f'{k}={str(v)}' for k, v in sorted_params)
#
#         logger.debug(f"待签名字符串: {message}")
#
#         # 3. 加载私钥并签名（修正导入后的使用方式）
#         private_key = RSA.import_key(private_key.encode('utf-8'))  # 确保私钥为字节流
#         h = SHA256.new(message.encode('utf-8'))
#         # 注意：此处应为 PKCS1_v1_5.new(private_key)，而非 pkcs1_15
#         signer = PKCS1_v1_5.new(private_key)
#         signature = signer.sign(h)
#
#         # 4. Base64编码
#         sign = base64.b64encode(signature).decode('utf-8')
#         logger.debug(f"签名结果: {sign}")
#
#         return sign
#     except Exception as e:
#         logger.error(f"生成签名失败: {str(e)}")
#         raise
#
#
# def verify_sign(params, public_key):
#     """验证签名 (使用 pycryptodome 实现)"""
#     try:
#         sign = params.get('sign', None)
#         sign_type = params.get('sign_type', 'RSA2')
#
#         if not sign:
#             logger.error("缺少签名参数")
#             return False
#
#         # 复制参数并移除签名相关字段
#         verify_params = params.copy()
#         verify_params.pop('sign', None)
#         verify_params.pop('sign_type', None)
#
#         # 过滤空值参数并排序
#         filtered_params = {k: v for k, v in verify_params.items() if v is not None and v != ''}
#         sorted_params = sorted(filtered_params.items(), key=lambda x: x[0])
#         message = '&'.join(f"{k}={v}" for k, v in sorted_params)
#
#         logger.debug(f"待验证字符串: {message}")
#         logger.debug(f"收到的签名: {sign}")
#
#         # 加载公钥并验证（修正导入后的使用方式）
#         public_key = RSA.import_key(public_key.encode('utf-8'))  # 确保公钥为字节流
#         h = SHA256.new(message.encode('utf-8'))
#         signature = base64.b64decode(sign)
#
#         # 尝试验证签名（使用 PKCS1_v1_5 而非 pkcs1_15）
#         try:
#             verifier = PKCS1_v1_5.new(public_key)
#             verifier.verify(h, signature)
#             logger.debug("签名验证成功")
#             return True
#         except (ValueError, TypeError) as e:
#             logger.error(f"签名验证失败: {str(e)}")
#             return False
#
#     except Exception as e:
#         logger.error(f"验证签名过程中出错: {str(e)}")
#         return False
#
#
# # 其他函数（create_alipay_order、query_order）保持不变，仅依赖上述签名函数
#
#
#
#
